import React, { useReducer } from "react";
import {Button} from 'antd';
const DemoUseReducer = () => {
    // /* number为更新后的state值,  dispatchNumbner 为当前的派发函数 */
    // const [ number , dispatchNumbner ] = useReducer((state,action)=>{
    //     const { payload , name  } = action
    //     /* return的值为新的state */
    //     switch(name){
    //         case 'add':
    //             return state + 1
    //         case 'sub':
    //             return state - 1 
    //         case 'reset':
    //             return payload       
    //     }
    //     return state
    // },502)
    // return (
    //     <div>
    //         当前值： {number}
    //         {/* 派发更新 */}
    //         <Button type="primary" onClick={()=>dispatchNumbner({name:'add'})}> 增加 </Button>
    //         <Button type="primary" onClick={()=>dispatchNumbner({name:'sub'})}> 减少 </Button>
    //         <Button type="primary" onClick={()=>dispatchNumbner({name:'reset',payload:502})}> 重置 </Button>
    //     </div>
    // )

    
    const init = (val) => {
        return {number: val}
    }
    const reducer = (state,action) => {
        switch(action.type){
            case 'add':
                return {number: state.number + 1}
            case 'sub':
                return {number: state.number - 1}
            default:
                throw new Error()
        }
    }
    const [state, dispatch] = useReducer(reducer, 1024, init); // 第二个参数为初始值，第三个参数为初始化函数
    return (
        <>
            当前值： {state.number}
            <Button type="primary" onClick={()=>dispatch({type:'add'})}> + </Button>
            <Button type="primary" onClick={()=>dispatch({type:'sub'})}> - </Button>
        </>
    )
}
export default DemoUseReducer;